package com.dorm.cj.dr.demo;

import com.dorm.cj.dr.MyEvent;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

import java.util.Iterator;
import java.util.List;

/**
 * disruptor 操作工具类
 */
public class DisruptorQueue {

    private Disruptor<MyEvent> disruptor;
    private RingBuffer<MyEvent> ringBuffer;

    public DisruptorQueue(Disruptor<MyEvent> disruptor) {
        this.disruptor = disruptor;
        this.ringBuffer = disruptor.getRingBuffer();
        this.disruptor.start();
    }

    public void add(Object data) {
        long sequence = this.ringBuffer.next();
        try {
            MyEvent myEvent = this.ringBuffer.get(sequence);
            myEvent.setData(data);
        } finally {
            this.ringBuffer.publish(sequence);
        }
    }

    public void addAll(List<Object> lists) {
        Iterator<Object> iterator = lists.iterator();
        while (iterator.hasNext()) {
            Object data = iterator.next();
            this.add(data);
        }
    }

    public long cursor() {
        return this.disruptor.getRingBuffer().getCursor();
    }

    public void shutdown() {
        this.disruptor.shutdown();
    }

    public Disruptor<MyEvent> getDisruptor() {
        return disruptor;
    }

    public void setDisruptor(Disruptor<MyEvent> disruptor) {
        this.disruptor = disruptor;
    }

    public RingBuffer<MyEvent> getRingBuffer() {
        return ringBuffer;
    }

    public void setRingBuffer(RingBuffer<MyEvent> ringBuffer) {
        this.ringBuffer = ringBuffer;
    }
}
